﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using Blazing.BusinessObjects.Tagging;
using System.BusinessObjects.Transactions;
using Blazing.BusinessObjects.Cms;

namespace Blazing.BusinessObjects.Queries
{
    public class QrySearchPagesByTaxonomyTags
    {
        public static IQuery Query(IList<TaxonomyTag> tags, Site site)
        {
            return Query(tags, site, false);
        }
        /// <summary>
        /// works by inner joining taxonomytags on each term to create a filter,
        /// </summary>
        public static IQuery Query(IList<TaxonomyTag> tags, Site site, bool order)
        {
            string hql = @"select c1 from Contentpage c1 
                           {0}
                           where c1.Site.ID = :site and {1}
                           {2}";

            //works by inner joining taxonomytags on each term to create a filter,
            //plz redo if you have a better solution...
            string tables = "";
            string wherelist = "";
            string orderlist = "order by c1.CreatedDate desc";
            for (int i = 0; i < tags.Count; i++)
            {
                tables += string.Format(" join c1.TaxonomyTags ptt{0} ", i);
                if (wherelist.Length > 0)
                    wherelist += " and";
                wherelist += string.Format(" ptt{0}.ID = :tid{0} ", i);
            }

            IQuery qry = UnitOfWork.CurrentSession.CreateQuery(string.Format(hql, tables, wherelist, order ? orderlist : ""));

            for (int i = 0; i < tags.Count; i++)
            {
                qry.SetParameter("tid" + i, tags[i].ID);
            }

            qry.SetParameter("site", site.ID);

            qry.SetCacheable(true);
            return qry;
        }
    }
}
